﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YJKArch.Utils;
using HYOpeningCommon.DataEnum;
using HYOpeningCommon.OpeningEX;
using HYOpeningCommon.Public;
using HYOpeningCreate.Cmd;

namespace HYOpeningCreate.ConfigForm
{
	public partial class OpeningSignMainForm : ConfigDataBaseForm
	{
		public OpeningSignMainForm(WindowHandle _hWndRevit, UIDocument uiDoc, ref Dictionary<Element, bool> lstElem)
		{
			this.InitializeComponent();
			WinDPIManager.GetWinFormXYDpi(ref this.m_dXScale, ref this.m_dYScale);
			this.m_uiDoc = uiDoc;
			this.m_doc = uiDoc.Document;
			this.m_nExHeight = base.Height;
			this.m_nUnExHeight = Convert.ToInt32(460.0 * this.m_dYScale);
			this.m_nHeightPanelDimensionSet = this.panelDimensionSet.Height;
			base.SetFormLocation(this.strXmlPath);
			lstElem = this.m_lstElem;
			this.m_hWndRevit = _hWndRevit;
			this.dataGridView.RowHeadersVisible = false;
			this.dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
			this.dataGridView.MultiSelect = false;
			this.dataGridView.Columns[4].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
			this.comBoxRectOpening.Items.Add("底标高");
			this.comBoxRectOpening.Items.Add("中心标高");
			this.comBoxRectOpening.Items.Add("顶标高");
			this.comBoxCircleOpening.Items.Add("底标高");
			this.comBoxCircleOpening.Items.Add("中心标高");
			this.comBoxCircleOpening.Items.Add("顶标高");
			this.SetHistoryData();
			this.GetCurrentViewHeight(ref this.m_dCurViewHeight);
			this.SetDataGridViewWidth();
			this.panelDimensionSet.Size = new Size(this.panelDimensionSet.Width, 0);
			base.Height = this.m_nUnExHeight;
		}

		private void SetHistoryData()
		{
			try
			{
				XmlDocument xmlDocument = new XmlDocument();
				if (File.Exists(this.strXmlPath))
				{
					XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
					xmlReaderSettings.IgnoreComments = true;
					XmlReader xmlReader = XmlReader.Create(this.strXmlPath, xmlReaderSettings);
					xmlDocument.Load(xmlReader);
					XmlNode xmlNode = xmlDocument.SelectSingleNode("HistoryData");
					this.txtMiniSize.Text = xmlNode.Attributes["MinDimensionSize"].Value;
					if (xmlNode.Attributes["DimensionMode"].Value == "引出标注")
					{
						this.radExtractDimension.Checked = true;
						this.txtDimenFront.Enabled = false;
					}
					else
					{
						this.radListDimension.Checked = true;
						this.txtDimenFront.Enabled = true;
					}
					this.txtDimenFront.Text = xmlNode.Attributes["DimenFrontText"].Value;
					string value = xmlNode.Attributes["DimRectOpening"].Value;
					this.comBoxRectOpening.SelectedIndex = this.GetDimLevel(value);
					value = xmlNode.Attributes["DimCircleOpening"].Value;
					this.comBoxCircleOpening.SelectedIndex = this.GetDimLevel(value);
					if (xmlNode.Attributes["DimOpeningPro"].Value == "是")
					{
						this.chkDimensionPro.Checked = true;
					}
					else
					{
						this.chkDimensionPro.Checked = false;
					}
					xmlReader.Close();
					xmlDocument.Save(this.strXmlPath);
				}
				else
				{
					this.comBoxCircleOpening.SelectedIndex = 1;
					this.comBoxRectOpening.SelectedIndex = 0;
				}
			}
			catch (Exception)
			{
				throw;
			}
		}

		private int GetDimLevel(string strDimLevel)
		{
			if (strDimLevel == "底标高")
			{
				return 0;
			}
			if (strDimLevel == "中心标高")
			{
				return 1;
			}
			return 2;
		}

		private void GetCurrentViewHeight(ref double dHeight)
		{
			ViewPlan viewPlan = this.m_doc.ActiveView as ViewPlan;
			if (viewPlan == null)
			{
				dHeight = -1.0;
				return;
			}
			Level genLevel = viewPlan.GenLevel;
			if (genLevel == null)
			{
				dHeight = -1.0;
				return;
			}
			double elevation = genLevel.Elevation;
			IEnumerable<Element> enumerable = new FilteredElementCollector(this.m_doc).OfClass(typeof(ViewPlan)).WhereElementIsNotElementType().ToElements();
			dHeight = double.MaxValue;
			foreach (Element element in enumerable)
			{
				genLevel = (element as ViewPlan).GenLevel;
				if (genLevel != null)
				{
					double elevation2 = genLevel.Elevation;
					if (Geometry.LessThan(elevation, elevation2) && Geometry.LessThan(elevation2 - elevation, dHeight))
					{
						dHeight = Math.Abs(elevation2 - elevation);
					}
				}
			}
		}

		private void SetDataGridViewWidth()
		{
			for (int i = 0; i < this.dataGridView.Columns.Count; i++)
			{
				this.dataGridView.Columns[i].Width = Convert.ToInt32((double)this.dataGridView.Columns[i].Width * this.m_dXScale);
			}
		}

		private void btnDimensionSet_Click(object sender, EventArgs e)
		{
			if (base.Height <= this.m_nUnExHeight)
			{
				this.panelDimensionSet.Size = new Size(this.panelDimensionSet.Width, this.m_nHeightPanelDimensionSet);
				base.Height = this.m_nExHeight;
				this.btnDimensionSet.Text = "标注设置︽";
				return;
			}
			this.panelDimensionSet.Size = new Size(this.panelDimensionSet.Width, 0);
			base.Height = this.m_nUnExHeight;
			this.btnDimensionSet.Text = "标注设置︾";
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private void OpeningSignMainForm_FormClosed(object sender, FormClosedEventArgs e)
		{
			try
			{
				XmlDocument xmlDocument = new XmlDocument();
				XmlReader xmlReader = null;
				bool flag = false;
				XmlElement xmlElement;
				if (File.Exists(this.strXmlPath))
				{
					flag = true;
					XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
					xmlReaderSettings.IgnoreComments = true;
					xmlReader = XmlReader.Create(this.strXmlPath, xmlReaderSettings);
					xmlDocument.Load(xmlReader);
					xmlElement = xmlDocument.DocumentElement;
				}
				else
				{
					XmlDeclaration newChild = xmlDocument.CreateXmlDeclaration("1.0", "gb2312", null);
					xmlDocument.AppendChild(newChild);
					xmlElement = xmlDocument.CreateElement("HistoryData");
					xmlDocument.AppendChild(xmlElement);
				}
				xmlElement.SetAttribute("LocationX", base.Location.X.ToString());
				xmlElement.SetAttribute("LocationY", base.Location.Y.ToString());
				if (this.txtMiniSize.Text == "")
				{
					this.txtMiniSize.Text = "0";
				}
				xmlElement.SetAttribute("MinDimensionSize", this.txtMiniSize.Text);
				if (this.radExtractDimension.Checked)
				{
					xmlElement.SetAttribute("DimensionMode", this.radExtractDimension.Text);
				}
				else
				{
					xmlElement.SetAttribute("DimensionMode", this.radListDimension.Text);
				}
				xmlElement.SetAttribute("DimenFrontText", this.txtDimenFront.Text);
				xmlElement.SetAttribute("DimRectOpening", this.comBoxRectOpening.SelectedText);
				xmlElement.SetAttribute("DimCircleOpening", this.comBoxCircleOpening.SelectedText);
				if (this.chkDimensionPro.Checked)
				{
					xmlElement.SetAttribute("DimOpeningPro", "是");
				}
				else
				{
					xmlElement.SetAttribute("DimOpeningPro", "否");
				}
				if (flag)
				{
					xmlReader.Close();
				}
				xmlDocument.Save(this.strXmlPath);
			}
			catch (Exception)
			{
				throw;
			}
			CommonInterface.KeyEsc(this.m_hWndRevit.Handle);
		}

		private void OpeningSignMainForm_Shown(object sender, EventArgs e)
		{
			Dictionary<Element, bool> openings = new Dictionary<Element, bool>();
			this.GetMatchConditionOpening(ref openings);
			CmdOpeningDimension.SetOpenings(openings);
		}

		private bool IsCut(double dMinZ, double dMaxZ)
		{
			Autodesk.Revit.DB.View activeView = this.m_doc.ActiveView;
			double elevation = activeView.GenLevel.Elevation;
			double num = (activeView as ViewPlan).GetViewRange().GetOffset(0) + 0.0;
			double num2 = elevation + num;
			return Geometry.LessThan(dMinZ, num2) && Geometry.LessThan(num2, dMaxZ);
		}

		private bool IsBelongCurrentPlan(double dMinZ, double dMaxZ)
		{
			double elevation = this.m_doc.ActiveView.GenLevel.Elevation;
			return !Geometry.LessThan(dMaxZ, elevation) && !Geometry.LessThan(elevation + this.m_dCurViewHeight, dMinZ) && !Geometry.IsEqual(elevation + this.m_dCurViewHeight, dMinZ);
		}

		private void GetOpeningDatas()
		{
			this.m_lstElem.Clear();
			foreach (Element element in new FilteredElementCollector(this.m_doc, this.m_doc.ActiveView.Id).OfCategory(BuiltInCategory.OST_GenericModel).WhereElementIsNotElementType().ToElements().Cast<Element>().ToList<Element>())
			{
				if (OpeningXData.IsIncludeSchema(element))
				{
					this.m_lstElem.Add(element, true);
				}
			}
		}

		private void GetMatchConditionOpening(ref Dictionary<Element, bool> lstElem)
		{
			this.GetOpeningDatas();
			double val = AssistFunc.mmToFeet(Convert.ToDouble(this.txtMiniSize.Text));
			OpeningXData openingXData = new OpeningXData();
			if (openingXData == null)
			{
				return;
			}
			this.dataGridView.AllowUserToAddRows = true;
			foreach (Element element in this.m_lstElem.Keys)
			{
				FamilyInstance familyInstance = element as FamilyInstance;
				if (familyInstance != null)
				{
					if (familyInstance.Host is FamilyInstance)
					{
						Element element2 = familyInstance.Host as FamilyInstance;
						int num = -2001320;
						if (element2.Category.Id.IntegerValue == num)
						{
							continue;
						}
					}
					openingXData.ReadOpeningXData(element);
					if (familyInstance.Host is Floor)
					{
						ElementId levelId = familyInstance.LevelId;
						if (levelId == null || levelId.IntegerValue == -1)
						{
							continue;
						}
						Level level = this.m_doc.GetElement(levelId) as Level;
						if (level == null)
						{
							continue;
						}
						Level genLevel = this.m_doc.ActiveView.GenLevel;
						if (level.UniqueId != genLevel.UniqueId)
						{
							continue;
						}
					}
					else if ((Geometry.LessThan(openingXData.m_dWidth, val) && Geometry.LessThan(openingXData.m_dHeight, val)) || !this.IsBelongCurrentPlan(openingXData.m_dMinZ, openingXData.m_dMaxZ))
					{
						continue;
					}
					if (familyInstance.Host is Floor)
					{
						this.dataGridView.Rows.Add(new object[]
						{
							this.dataGridView.Rows.Count,
							openingXData.m_strAxisX,
							openingXData.m_strAxisY,
							openingXData.m_strHostObject,
							openingXData.m_strOpeningSize
						});
						this.dataGridView.Rows[this.dataGridView.Rows.Count - 2].Tag = element;
						lstElem.Add(element, false);
					}
					else if (openingXData.m_eOpeningProfile == 1)
					{
						this.dataGridView.Rows.Add(new object[]
						{
							this.dataGridView.Rows.Count,
							openingXData.m_strAxisX,
							openingXData.m_strAxisY,
							openingXData.m_strHostObject,
							openingXData.m_strOpeningSize
						});
						this.dataGridView.Rows[this.dataGridView.Rows.Count - 2].Tag = element;
						if (!this.IsCut(openingXData.m_dMinZ, openingXData.m_dMaxZ))
						{
							lstElem.Add(element, true);
						}
						else
						{
							lstElem.Add(element, false);
						}
					}
					else
					{
						this.dataGridView.Rows.Add(new object[]
						{
							this.dataGridView.Rows.Count,
							openingXData.m_strAxisX,
							openingXData.m_strAxisY,
							openingXData.m_strHostObject,
							openingXData.m_strOpeningSize
						});
						this.dataGridView.Rows[this.dataGridView.Rows.Count - 2].Tag = element;
						lstElem.Add(element, true);
					}
				}
			}
			this.dataGridView.AllowUserToAddRows = false;
		}

		private void txtMiniSize_TextChanged(object sender, EventArgs e)
		{
			if (this.txtMiniSize.Text == string.Empty)
			{
				return;
			}
			if (this.txtMiniSize.Text == " ")
			{
				this.txtMiniSize.Text = "";
				return;
			}
			this.dataGridView.Rows.Clear();
			Dictionary<Element, bool> openings = new Dictionary<Element, bool>();
			this.GetMatchConditionOpening(ref openings);
			CmdOpeningDimension.SetOpenings(openings);
		}

		private void radExtractDimension_CheckedChanged(object sender, EventArgs e)
		{
			this.txtDimenFront.Enabled = false;
			this.chkDimensionPro.Enabled = true;
		}

		private void radListDimension_CheckedChanged(object sender, EventArgs e)
		{
			this.txtDimenFront.Enabled = true;
			this.chkDimensionPro.Enabled = false;
		}

		private void DoubleClick2Location(Element elem)
		{
			if (elem == null)
			{
				return;
			}
			List<Element> list = new List<Element>();
			list.Add(elem);
			RevitVersionFuncs.SetSelection(this.m_uiDoc.Selection, list);
			UIView uiview = null;
			foreach (UIView uiview2 in this.m_uiDoc.GetOpenUIViews())
			{
				if (uiview2.ViewId.Equals(this.m_uiDoc.ActiveView.Id))
				{
					uiview = uiview2;
					break;
				}
			}
			BoundingBoxXYZ boundingBoxXYZ = elem.get_BoundingBox(this.m_uiDoc.Document.ActiveView);
			XYZ xyz = boundingBoxXYZ.Min;
			XYZ xyz2 = boundingBoxXYZ.Max;
			XYZ xyz3 = (xyz2 = xyz).Normalize();
			xyz += xyz3.Negate() * 30.0;
			xyz2 += xyz3 * 30.0;
			uiview.ZoomAndCenterRectangle(xyz, xyz2);
		}

		private void btnCheck_Click(object sender, EventArgs e)
		{
			if (this.dataGridView.SelectedRows.Count == 0)
			{
				return;
			}
			Element elem = this.dataGridView.SelectedRows[0].Tag as Element;
			this.DoubleClick2Location(elem);
		}

		private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex == -1)
			{
				return;
			}
			Element elem = this.dataGridView.Rows[e.RowIndex].Tag as Element;
			this.DoubleClick2Location(elem);
		}

		public bool IsRadExtractDimensionChecked()
		{
			return this.radExtractDimension.Checked;
		}

		public void GetDimSelected(ref EDimItemType rectOpeningDimType, ref EDimItemType circleOpeningDimType)
		{
			if (this.comBoxRectOpening.SelectedIndex == 0)
			{
				rectOpeningDimType = EDimItemType.eBottom;
			}
			else if (this.comBoxRectOpening.SelectedIndex == 1)
			{
				rectOpeningDimType = EDimItemType.eMid;
			}
			else if (this.comBoxRectOpening.SelectedIndex == 2)
			{
				rectOpeningDimType = EDimItemType.eTop;
			}
			if (this.comBoxCircleOpening.SelectedIndex == 0)
			{
				circleOpeningDimType = EDimItemType.eBottom;
				return;
			}
			if (this.comBoxCircleOpening.SelectedIndex == 1)
			{
				circleOpeningDimType = EDimItemType.eMid;
				return;
			}
			if (this.comBoxCircleOpening.SelectedIndex == 2)
			{
				circleOpeningDimType = EDimItemType.eTop;
			}
		}

		public string GetDimPrefix()
		{
			return this.txtDimenFront.Text;
		}

		public bool IsChkDimensionPro()
		{
			return this.chkDimensionPro.Checked;
		}

		private void OpeningSignMainForm_KeyDown(object sender, KeyEventArgs e)
		{
			try
			{
				Keys keyCode = e.KeyCode;
				if (keyCode == Keys.Escape)
				{
					base.Close();
				}
			}
			catch
			{
			}
		}

		private string strXmlPath = Product.UserDataLocation + "\\OpeningSignMainForm.xml";

		private Document m_doc;

		private UIDocument m_uiDoc;

		private int m_nExHeight;

		private int m_nUnExHeight = 460;

		private int m_nHeightPanelDimensionSet;

		private Dictionary<Element, bool> m_lstElem = new Dictionary<Element, bool>();

		private WindowHandle m_hWndRevit;

		private double m_dXScale;

		private double m_dYScale;

		private double m_dCurViewHeight;
	}
}
